<script setup lang="ts">
import { ref } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
// import { updatePassword } from "@/api/user";

const router = useRouter();

// 表单数据
const form = ref({
  oldPassword: "",
  newPassword: "",
  confirmPassword: ""
});

// 加载状态
const loading = ref(false);

// 表单验证规则
const rules = {
  oldPassword: [{ required: true, message: "请输入原密码", trigger: "blur" }],
  newPassword: [
    { required: true, message: "请输入新密码", trigger: "blur" },
    { min: 6, max: 20, message: "长度在6到20个字符", trigger: "blur" }
  ],
  confirmPassword: [
    { required: true, message: "请确认新密码", trigger: "blur" },
    {
      validator: (_rule, value, callback) => {
        if (value !== form.value.newPassword) {
          callback(new Error("两次输入密码不一致"));
        } else {
          callback();
        }
      },
      trigger: "blur"
    }
  ]
};

const formRef = ref();

// 提交重置密码
const onSubmit = async () => {
  try {
    loading.value = true;
    await formRef.value.validate();
    const res = await updatePassword(
      form.value.oldPassword,
      form.value.newPassword
    );
    if (res.code === 0) {
      ElMessage.success("密码修改成功");
      router.push("/login"); // 跳转至登录页
    } else {
      ElMessage.error(res.message || "修改失败");
    }
  } catch (error) {
    ElMessage.error("验证失败或网络异常");
  } finally {
    loading.value = false;
  }
};
</script>

<template>
  <div class="h-screen w-screen bg-gray-100 px-4 py-4">
    <el-card
      class="w-full max-w-md shadow-xl rounded-xl transition-transform transform hover:scale-[1.01]"
    >
      <div class="text-center mb-6">
        <h2 class="text-2xl font-bold text-gray-800">修改密码</h2>
        <p class="text-sm text-gray-500 mt-1">请输入原密码并设置新密码</p>
      </div>

      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="130px"
        class="space-y-4"
      >
        <el-form-item label="原密码" prop="oldPassword">
          <el-input
            v-model="form.oldPassword"
            show-password
            placeholder="请输入原密码"
          />
        </el-form-item>

        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="form.newPassword"
            show-password
            placeholder="请输入新密码"
          />
        </el-form-item>

        <el-form-item label="确认新密码" prop="confirmPassword">
          <el-input
            v-model="form.confirmPassword"
            show-password
            placeholder="请再次输入新密码"
          />
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            @click="onSubmit"
            class="w-full py-3 font-medium rounded-lg transition-colors"
            :loading="loading"
          >
            {{ loading ? "提交中..." : "保存修改" }}
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<style scoped lang="scss">
/* 如果需要额外样式可以在这里写 */
</style>
